package com.app.lcl.utils;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	public static final SessionFactory sessionFactory;
	private HibernateUtil(){}//无参的构造器
	static {   
		  try
		  {
		      //采用默认的hibernate.cfg.xml来启动一个Configuration的实例
			  Configuration config=new Configuration().configure();
			  StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
			  StandardServiceRegistry ssr = ssrb.build();
			  //由Configuration的实例来创建一个SessionFactory实例
		      sessionFactory = config.buildSessionFactory(ssr);
		   }
		  catch (Throwable ex)
		  {
		      // Make sure you log the exception, as it might be swallowed
		      System.err.println("Initial SessionFactory creation failed." + ex);
		      throw new ExceptionInInitializerError(ex);
		  } 
	 } 
	//ThreadLocal是隔离多个线程的数据共享，不存在多个线程之间共享资源,因此不再需要对线程同步
	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
	public static Session currentSession() throws HibernateException {
	     Session s = (Session) session.get();
	     //如果该线程还没有Session,则创建一个新的Session
	     if (s == null){
	         s = sessionFactory.openSession();
	         //将获得的Session变量存储在ThreadLocal变量session里
	         session.set(s);
	       }
	     return s;
	  }
	
	 public static void closeSession() throws HibernateException {
	        Session s = (Session) session.get();
	        if (s != null)s.close();
	        session.set(null);
	  }
	 
	 public static Session getThreadLocalSession() {   
	        Session s = (Session) session.get();   
	        if (s == null) {   
	        	s = getSession();   
	            session.set(s);   
	        }   
	        return s;   
	  }  

	 public static SessionFactory getSessionFactory() {   
	        return sessionFactory;   
	  }  
	 
	 public static Session getSession() {   
	        return sessionFactory.openSession();   
	  }   
	 
	 public static void add(Object entity) {   
	        Session s = null;   
	        Transaction tx = null;   
	        try {   
	            s = HibernateUtil.getSession();   
	            tx = s.beginTransaction();   
	            s.save(entity);   
	            tx.commit();   
	        } finally {   
	            if (s != null)   
	                s.close();   
	        }   
	 }   

	 public static void update(Object entity) {   
	        Session s = null;   
	        Transaction tx = null;   
	        try {   
	            s = HibernateUtil.getSession();   
	            tx = s.beginTransaction();   
	            s.update(entity);   
	            tx.commit();   
	        } finally {   
	            if (s != null)   
	                s.close();   
	        }   
	 }   

	 public static void delete(Object entity) {   
	        Session s = null;   
	        Transaction tx = null;   
	        try {   
	            s = HibernateUtil.getSession();   
	            tx = s.beginTransaction();   
	            s.delete(entity);   
	            tx.commit();   
	        } finally {   
	            if (s != null)   
	                s.close();   
	        }   
	 }   

	 public static Object get(Class<?> clazz, Serializable id) {   
	        Session s = null;   
	        try {   
	            s = HibernateUtil.getSession();   
	            Object obj = s.get(clazz, id);   
	            return obj;   
	        } finally {   
	            if (s != null)   
	                s.close();   
	        }   
	 }
}
